package com.sec.typhoondatapush.service;

import com.sec.typhoondatapush.config.QuartzJobFactory;
import com.sec.typhoondatapush.entity.JobConfig;
import com.sec.typhoondatapush.enums.ConfigEnum;
import com.sec.typhoondatapush.repository.JobConfigRepository;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 动态job的服务的实现
 *
 * @author zhuwq
 * @version V1.0
 * @date 2018/7/30- 15:11
 */
@Slf4j
@Service
public class QuartzTableService {

    private static final String STATUS_STOP = "1";
    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private JobConfigRepository jobConfigRepository;
    @Autowired
    private MongoOperations mongoOperations;

    /**
     * 启动/停止任务
     *
     * @return: void
     */
    public void updateStatus(ObjectId id, String status) throws Exception {

        Optional<JobConfig> existsId = jobConfigRepository.findById(id);
        JobConfig jobConfig;
        //判断是否有此ID的数据
        if (!existsId.isPresent()) {
            log.error("未找到此定时任务{}", id);
            throw new RuntimeException("未找到此定时任务");
        } else {
            jobConfig = existsId.get();
        }

        if (STATUS_STOP.equals(status)) {
            // stop 禁用
            jobConfig.setStatus(ConfigEnum.STATUS_STOP.getCode());
            jobConfigRepository.save(jobConfig);
            deleteJob(jobConfig);
        } else {
            //start 启用
            jobConfig.setStatus(ConfigEnum.STATUS_START.getCode());
            jobConfigRepository.save(jobConfig);
            addJob(jobConfig);
        }
    }

    /**
     * 启动所有的任务
     *
     * @return: void
     */
    public void startAllJobs() {
        List<JobConfig> jobConfigList = jobConfigRepository.findAll();
        for (JobConfig jobConfig : jobConfigList) {
            if (ConfigEnum.STATUS_START.getCode().equals(jobConfig.getStatus())) {
                try {
                    addJob(jobConfig);
                } catch (SchedulerException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 修改cron表达式
     *
     * @param id
     * @param cronSchedule
     * @return: void
     */
    public void updateCron(ObjectId id, String cronSchedule) {

        Optional<JobConfig> existsId = jobConfigRepository.findById(id);
        JobConfig jobConfig;
        String oldCron;
        //判断是否有此ID的数据
        if (!existsId.isPresent()) {
            log.error("未找到此定时任务{}", id);
            throw new RuntimeException("未找到此定时任务");
        } else {
            jobConfig = existsId.get();
            oldCron = jobConfig.getCron();
            jobConfig.setCron(cronSchedule);
            mongoOperations.save(jobConfig);
        }

        log.info("更新定时器从 " + oldCron + " 变为 " + cronSchedule);
        try {
            addJob(jobConfigRepository.findById(id).get());
        } catch (SchedulerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 增加任务/按照新的规则重启任务
     *
     * @param jobConfig 任务的配置
     * @return: void
     */
    private void addJob(JobConfig jobConfig) throws SchedulerException {
        //得到调度器
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = this.getJobKey(jobConfig);
        //获得触发器
        TriggerKey triggerKey = TriggerKey.triggerKey(jobConfig.getName(), jobConfig.getGroup());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        //判断触发器是否存在（如果存在说明之前运行过但是在当前被禁用了，如果不存在说明一次都没运行过）
        if (trigger == null) {
            //新建一个工作任务 指定任务类型为串接进行的
            JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(jobKey).build();
            //将工作添加到工作任务当中去
            jobDetail.getJobDataMap().put(QuartzJobFactory.SCHEDULEJOBKEY, jobConfig);
            //将cron表达式进行转换
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobConfig.getCron());
            //创建触发器并将cron表达式对象给塞入
            trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
            //在调度器中将触发器和任务进行组合
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobConfig.getCron());
            //按照新的规则进行 withMisfireHandlingInstructionDoNothing 平滑过渡下个新的周期
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder.withMisfireHandlingInstructionDoNothing()).build();
            //重启
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }

    /**
     * 删除任务
     *
     * @param jobConfig 任务的配置
     * @return: void
     */
    private void deleteJob(JobConfig jobConfig) throws SchedulerException {
        //得到调度器
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        //找到key值
        JobKey jobKey = this.getJobKey(jobConfig);
        //从触发器找到此任务然后进行删除
        scheduler.deleteJob(jobKey);
    }

    /**
     * 根据name和group得到任务的key
     *
     * @param jobConfig 任务的配置
     * @return jobKey    任务的key
     */
    private JobKey getJobKey(JobConfig jobConfig) {
        return getJobKey(jobConfig.getName(), jobConfig.getGroup());
    }

    private JobKey getJobKey(String name, String group) {
        return JobKey.jobKey(name, group);
    }
}
